package com.aerfafish.spider.neo4j.spider.service.impl;

import com.aerfafish.spider.neo4j.dao.CompanyHoldShare;
import com.aerfafish.spider.neo4j.repository.CompanyHoldShareRepository;
import com.aerfafish.spider.neo4j.spider.service.CompanyShareRelationService;
import org.neo4j.driver.exceptions.TransientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class CompanyShareRelationServiceImpl implements CompanyShareRelationService {

    @Autowired
    CompanyHoldShareRepository companyHoldShareRepository;

    @Override
    public void save(CompanyHoldShare companyHoldShare) throws Exception {
        save(companyHoldShare, companyHoldShare.getCompany().getCode(), companyHoldShare.getShare().getCode());
    }

    @Override
    public void save(CompanyHoldShare companyHoldShare, String companyCode, String shareCode) throws Exception {
        save(companyCode, shareCode, companyHoldShare.getProportion(), companyHoldShare.getSharesNum(), companyHoldShare.getSharesValue());
    }

    @Override
    public void save(String companyCode, String shareCode, Float proportion, Float sharesNum, Float sharesValue) throws Exception {
        if (companyCode == null || shareCode == null || proportion == null || sharesNum == null || sharesValue == null) {
            throw new Exception("some param is null");
        }
        Pattern pattern = Pattern.compile("^[^0-9]*([0-9]*$)");
        Matcher matcher = pattern.matcher(shareCode);
        // 去掉前面的字母，也就是市场名字
        if (matcher.find()) {
            shareCode = matcher.group(1);
        } else {
            throw new Exception("saveCompanyShare: match share code error");
        }

        try {
            companyHoldShareRepository.save(companyCode, shareCode, proportion, sharesNum, sharesValue);
        } catch (TransientException | InvalidDataAccessApiUsageException e) {
            try {
                companyHoldShareRepository.save(companyCode, shareCode, proportion, sharesNum, sharesValue);
            } catch (TransientException | InvalidDataAccessApiUsageException e0) {
                companyHoldShareRepository.save(companyCode, shareCode, proportion, sharesNum, sharesValue);
            }
        }

    }
}
